package com.njtoyo.taxi.admin.rest.controller.business;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.hutool.poi.excel.StyleSet;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njtoyo.taxi.admin.aop.PermissionScope;
import com.njtoyo.taxi.admin.rest.presenter.business.simple_call_ride.SimpleCallRideVO;
import com.njtoyo.taxi.admin.rest.presenter.business.taxis.TaxiPresenter;
import com.njtoyo.taxi.admin.rest.presenter.business.taxis.TaxiQueryActivationCountPresenter;
import com.njtoyo.taxi.admin.rest.presenter.business.taxis.TaxisPresenter;
import com.njtoyo.taxi.admin.rest.readfile.taxis.RegisterBatchResult;
import com.njtoyo.taxi.admin.rest.readfile.taxis.ScrapBatcResult;
import com.njtoyo.taxi.admin.rest.wrapper.business.taxis.*;
import com.njtoyo.taxi.admin.service.business.TaxiService;
import com.njtoyo.taxi.entity.backend.AdminUser;
import com.taxi.entity.common.RestResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.CellStyle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Api(value = "车辆", tags = "车辆")
@RequestMapping("business/taxi")
public class TaxisController {
    @Autowired
    private TaxiService taxiService;


    @GetMapping()
    @ApiOperation(value = "车辆列表", notes = "权限：taxis_list")
    @PermissionScope(names = {"taxis_list"})
    RestResult<Page<TaxisPresenter>> taxisList(@ModelAttribute("admin") AdminUser adminUser, TaxiQueryListWrapper wrapper) {
        return taxiService.selectListTaxi(adminUser, wrapper);
    }


    @PostMapping("")
    @ApiOperation(value = "注册车辆", notes = "注册车辆,权限：taxis_register")
    @PermissionScope(names = {"taxis_register"})
    RestResult register(@Valid @RequestBody TaxiRegisterWrapper wrapper) {
        return taxiService.register(wrapper);
    }


    @PostMapping("/register-batch")
    @ApiOperation(value = "通过Excel批量注册车辆", notes = "通过Excel批量注册车辆 , 使用模板文件:TaxiRegisterBatch.xlsx,权限：taxis_register_batch")
    @PermissionScope(names = {"taxis_register_batch"})
    RestResult<RegisterBatchResult> registerBatch(@RequestParam(value = "file", required = true) MultipartFile file,
                                                  @RequestParam(value = "companyId", required = true) Long companyId) throws IOException {
        RegisterBatchWrapper wrapper = new RegisterBatchWrapper();
        wrapper.setCompanyId(companyId);
        return taxiService.registerBatch(file, wrapper);
    }

    @PatchMapping("/{id}")
    @ApiOperation(value = "修改车辆", notes = "修改车辆,权限：taxis_update_taxis")
    @PermissionScope(names = {"taxis_update_taxis"})
    RestResult updateTaxis(@PathVariable("id") Long id, @Valid @RequestBody TaxiUpdateWrapper wrapper) {
        return taxiService.updateTaxi(id, wrapper);
    }

    @PatchMapping("/{id}/scrap")
    @ApiOperation(value = "报废车辆,设置可用", notes = "报废车辆,设置可用,权限：taxis_scrap")
    @PermissionScope(names = {"taxis_scrap"})
    RestResult updateTaxisScrap(@PathVariable("id") Long id, @Valid @RequestBody TaxiScrapWrapper wrapper) {
        return taxiService.updateTaxisScrap(id, wrapper);
    }

    @PatchMapping("/{id}/sendOrder")
    @ApiOperation(value = "激活派单", notes = "激活派单")
    RestResult sendOrder(@PathVariable("id") Long id) {
        return taxiService.sendOrder(id);
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除车辆", notes = "删除车辆,权限：taxis_delete_taxis")
    @PermissionScope(names = {"taxis_delete_taxis"})
    RestResult deleteTaxis(@PathVariable("id") Long id) {
        return taxiService.deleteTaxi(id);
    }


    @PostMapping("/scrap-batch")
    @ApiOperation(value = "通过Excel批量报废车辆", notes = "通过Excel批量报废车辆 ,使用模板文件:TaxiScrapBatch.xlsx,权限：taxis_scrap_batch")
    @PermissionScope(names = {"taxis_scrap_batch"})
    RestResult<ScrapBatcResult> scrapBatch(@RequestParam(value = "file", required = true) MultipartFile file) throws IOException {
        return taxiService.scrapBatch(file);
    }


    @GetMapping("/taxis-platenumber")
    @ApiOperation(value = "通过车牌查询车辆")
    RestResult<List<TaxiPresenter>> taxisListByPlateNumber(String plateNumber) {
        return taxiService.taxisListByPlateNumber(plateNumber);
    }

    @GetMapping("/export")
    @ApiOperation(value = "车辆批量导出", notes = "车辆批量导出,权限：taxis_batch_export")
    @PermissionScope(names = {"taxis_batch_export"})
    void TaxisBatchexport(@ModelAttribute("admin") AdminUser adminUser, TaxiQueryListWrapper wrapper,
                          HttpServletResponse response) throws IOException {
        wrapper.setSize(100000);
        RestResult<Page<TaxisPresenter>> restResult = taxiService.selectListTaxi(adminUser, wrapper);
        List<TaxisPresenter> pages = restResult.getData().getRecords();
        List<Map<String, Object>> rows = new ArrayList<>();
        if (CollUtil.isNotEmpty(pages)) {
            for (TaxisPresenter taxisPresenter : pages) {
                Map<String, Object> row = new HashMap<>();
                row.put("编号", taxisPresenter.getId());
                row.put("车牌号", taxisPresenter.getPlateNumber());
                row.put("地区", taxisPresenter.getCantonName());
                row.put("运力公司", taxisPresenter.getCompanyName());
                row.put("绑定司机", taxisPresenter.getCount());
                row.put("APP状态", taxisPresenter.getIsAvailable() ? "可用" : "不可用");
                row.put("注册时间", taxisPresenter.getCreatedAt().toString());
                row.put("更新时间", taxisPresenter.getUpdatedAt().toString());
                row.put("车机版本", taxisPresenter.getVersion());
                rows.add(row);
            }
        } else {
            Map<String, Object> row = new HashMap<>();
            row.put("编号", "");
            row.put("车牌号", "");
            row.put("地区", "");
            row.put("运力公司", "");
            row.put("绑定司机", "");
            row.put("APP状态", "");
            row.put("注册时间", "");
            row.put("更新时间", "");
            row.put("车机版本", "");
            rows.add(row);
        }
        ExcelWriter writer = ExcelUtil.getWriter();
        StyleSet style = writer.getStyleSet();
        CellStyle cellStyle = style.getHeadCellStyle();
        cellStyle.setWrapText(true);
        writer.write(rows, true);
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=cars.xls");
        ServletOutputStream out = response.getOutputStream();

        writer.flush(out, true);
        writer.close();
        IoUtil.close(out);
    }

    @GetMapping("/activation-count")
    @ApiOperation(value = "获取已激活车辆数", notes = "获取已激活车辆数，权限：taxis_list")
    @PermissionScope(names = {"taxis_list"})
    RestResult<TaxiQueryActivationCountPresenter> getActivationCount(@ModelAttribute("admin") AdminUser adminUser, QueryTaxiActivationCountWrapper wrapper) {
        return taxiService.getActivationCount(adminUser, wrapper);
    }


    @GetMapping("/getNearbyCarByPoint")
    RestResult getNearbyCarByPoint(@RequestParam(required = false) String lng,
                                   @RequestParam(required = false) String lat,
                                   @RequestParam(required = false, defaultValue = "all") String callMode) {
        if (StrUtil.isBlank(lng) || StrUtil.isBlank(lat)) {
            return RestResult.success();
        }
        return taxiService.getNearbyCarByPoint(lng, lat,callMode);
    }


    @PostMapping("/bindCC/{id}")
    RestResult bindCC(@PathVariable("id") Long id) {
        return taxiService.bindCC(id);
    }

}
